<?php

namespace haibao\user\data\payment\web;

class UserVip extends \haibao\user\data\BaseMysql {
    
	public function __construct(){
		parent::__construct('\haibao\user\model\data\payment\web\UserVip');
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_USER );
		$this->setReadPerformance(true);
	}
	
	public function getVipByUserId($userId){
	    $sql = 'select * from UserVip where UserId=%s and StartDate<=%s and EndDate>=%s limit 1';
	    $result = $this->query($sql, array(
	        $userId, date('Y-m-d'), date('Y-m-d')
	    ));
	    return $result->fetch_assoc();
	}
	
	public function getUserVipEndDate($userId){
	    $result = $this->query('select EndDate from UserVip where UserId=%s order by EndDate desc,Id desc limit 1', array(
	        $userId
	    ));
	    $endDate = null;
	    while ($result->fetch_assoc()){
	        $endDate = $result->getData('EndDate')->format('Y-m-d');
	    }
	    return $endDate;
	}
	
	/**
	 * 增加会员观看时长记录
	 */
	public function addUserVip($userId, $productId){
	    $productData = new \haibao\user\data\payment\VipProduct();
	    $product = $productData->getProductByProductId($productId);
	    $endDate = $this->getUserVipEndDate($userId);

	    if($endDate && ($endDate > date('Y-m-d'))){
            $startDate = date('Y-m-d', strtotime('+1 day', strtotime($endDate)));
        }else{
            $startDate = date('Y-m-d');
        }

	    $endDate = date('Y-m-d', strtotime('+'.intval($product['IncrMonth']).' month', strtotime($startDate)));
	    
	    $model = new \haibao\user\model\data\payment\web\UserVip();
	    $model->UserId = $userId;
	    $model->StartDate = $startDate;
	    $model->EndDate = $endDate;
	    $model->CreateTime = new \DateTime();
	    $this->add($model);
	    return $model->Id;
	}

}
